package dcsinstnce.server.accessers.impl;

import org.omg.CORBA.Object;

import dcsinstnce.pds.uchiha.corba.manager.CorbaManager;
import dcsinstnce.server.accessers.DataReaderListenerOperations;
import dcsinstnce.server.accessers.DataReaderOperations;
import dcsinstnce.server.domaines.RemoteDomaineManager;
import dcsinstnce.server.domaines.RemoteDomaineManagerHelper;
import dcsinstnce.server.interfaces.Suscriber;
import dcsinstnce.server.operations.Operation;
import dcsinstnce.server.operations.OperationType;
import dcsinstnce.server.operations.Replicated;
import dcsinstnce.server.topic.impl.TopicImpl;


public class DataReaderImpl implements DataReaderOperations,
		DataReaderListenerOperations {

	private TopicImpl topic;
	/**
	 * constructeur
	 * @param topic
	 */
	public DataReaderImpl(TopicImpl topic) {
		this.topic = topic;
	}

	@Override
	public void signale() {
		Operation operation = topic.getSuscriber().read(topic.getFullName());
		executeOperation(operation);
		if (operation.replicated == Replicated.isReplicated) {
			Object objRef = CorbaManager.getInstance().getReference(
					"RemoteDomaine");
			RemoteDomaineManager domaine = RemoteDomaineManagerHelper
					.narrow(objRef);
			operation.replicated = Replicated.isNotReplicated;
			Suscriber[] suscribers = domaine.getTopicsSuscribers(
					topic.getFullName(), null);
			if (suscribers[0] == null)
				return;
			for (int i = 0; i < suscribers.length; i++) {
					suscribers[i].publish(topic.getFullName(), operation);
			}
		}
	}
	/**
	 * 
	 * @param operation : opération à executer
	 */
	public void executeOperation(Operation operation) {
		if (operation.target.equals("cache")) {
			if (operation.type.value() == OperationType._create) {
				topic.createCache();
			}
			if (operation.type.value() == OperationType._delete) {
				topic.deleteCache();
			}
		} else if (operation.target.equals("topic")) {
			if (operation.type.value() == OperationType._create) {
				topic.createTopic(operation.data.data.extract_Value()
						.toString());
			} else if (operation.type.value() == OperationType._delete) {
				topic.deleteTopic(operation.data.data.extract_Value()
						.toString());
			}
		}
	}
}
